summaryrefslogtreecommitdiff
path: root/apps/web/app/shared/[token]/shared-entry-content.tsx
blob: aaa9892272ac03b592eea67ba04137513796f46b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"use client"

import { useEffect, useRef } from "react"
import {
  deserializeHighlightRange,
  applyHighlightToRange,
} from "@/lib/highlight-positioning"

interface SharedHighlightData {
  highlightedText: string
  textOffset: number
  textLength: number
  textPrefix: string
  textSuffix: string
}

interface SharedEntryContentProperties {
  sanitisedHtml: string
  highlightData: SharedHighlightData | null
}

export function SharedEntryContent({
  sanitisedHtml,
  highlightData,
}: SharedEntryContentProperties) {
  const containerReference = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const container = containerReference.current
    if (!container) return

    container.innerHTML = sanitisedHtml

    if (!highlightData) return

    const highlightRange = deserializeHighlightRange(container, highlightData)
    if (!highlightRange) return

    applyHighlightToRange(highlightRange, "shared-highlight", "yellow", false)

    requestAnimationFrame(() => {
      const markElement = container.querySelector(
        'mark[data-highlight-identifier="shared-highlight"]'
      )
      if (markElement) {
        markElement.scrollIntoView({ behavior: "smooth", block: "center" })
      }
    })
  }, [sanitisedHtml, highlightData])

  return (
    <div
      ref={containerReference}
      className="prose-reader text-text-secondary"
    />
  )
}